﻿using BusinessLogic.Connectivity.Entities;
using System;
using System.ServiceModel;
using BusinessLogic.BusinessEntity.Entities;


namespace BankApplication.BusinessLogic
{
	public class SessionManager : ISessionManager
	{
		protected SessionManager()
		{}

		private static ISessionManager instance;

		public static ISessionManager Instance
		{
			get 
			{
				if (instance == null)
				{
					instance = new SessionManager();
				}

				return instance;
			}
		}

		public string SessionTicket { get; set; }


		public void EstablishSession(Credentials credentials)
		{
			ServerResponse<User> response = ServerProxy.Instance.GetSessionTicket(credentials);

			// might throw CommunicationException

			if (response.ServerResponseCode == ServerResponseCode.Success)
			{
				var user = response.Payload;
				var userRoles = UsersManager.GetUserRoles(user.ID, response.Ticket);

				if (!userRoles.Contains(Role.BankEmployee))
				{
					throw new AuthorizationFailedException("You must have the 'Bank employee' access rights to run the application!");
				}

				SessionManager.Instance.SessionTicket = response.Ticket;
			}
			else
			{
				throw new AuthorizationFailedException("Wrong username and/or password!");
			}
		}


		public void Dispose()
		{
			SessionTicket = null;
		}
	}
}
